package com.tensquare.search.service;

import com.tensquare.entity.IdWorker;
import com.tensquare.entity.PageResult;
import com.tensquare.search.dao.ArticleDao;
import com.tensquare.search.pojo.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by WF on 2020/12/20 15:39
 */
@Service
public class ArticleService {
    @Autowired
    private ArticleDao articleDao;
    @Autowired
    private IdWorker idWorker;
    //1.条件带分页查询
    public PageResult<Article> search(String keywords, Integer page, Integer size) {
        //1.1)查询出分页对象
        Page<Article> articlePage = articleDao.findByTitleOrContentLike(keywords, keywords, PageRequest.of(page - 1, size));
        //1.2)返回自定义的分页对象
        return new PageResult<>(articlePage.getTotalElements(),articlePage.getContent());
    }

    //2. 添加到索引库
    public void add(Article article) {
        //2.1)生成主键
        long nextId = idWorker.nextId();
        article.setId(nextId + "");
        //2.2)添加到索引库中
        articleDao.save(article);
    }

    public Iterable<Article> findAll() {
        return  articleDao.findAll();
    }
}
